<?php

namespace polymerize\auth\module\login;


use app\common\InstanceTrait;
use app\common\LoginType;
use app\common\SmsType;
use app\model\OrderVipcart;
use app\model\User as UserModel;
use app\model\UserBehaviorLog;
use app\model\UserToken;
use app\model\UserVip;
use support\Cache;
use support\Redis;

class LoginByMobile
{
    use InstanceTrait;

    /**
     * 手机验证码登录[发送短信验证]
     *
     * @param int    $mobile
     * @param int    $smsCode
     * @param string $ref
     * @return array
     */
    public function loginByMobile(int $mobile, int $smsCode, string $ref): array
    {
        $expireTime = 2;
        $lockKey    = __METHOD__ . $mobile;
        $lock        = Redis::setNx($lockKey, 1);
        Redis::expire($lockKey, $expireTime);
        if (!$lock) return ['code' => 400, 'msg' => MANY_TIMES_REQUEST];
        $smsKey = 'SMS_CODE_' . md5($mobile . SmsType::SMS_CODE_API_LOGIN->value);
        if ($smsCode != Cache::get($smsKey)) return ['code' => 400, 'msg' => '短信验证码错误'];
        Cache::delete($smsKey);
        if (Redis::ttl($lockKey) == -1) Redis::expire($lockKey, $expireTime);             //防止死锁

        $where[] = ['mobile', '=', $mobile];
        $field   = 'id,mobile,status,c_time,avatar,login_type,ref';
        $user    = UserModel::where($where)->field($field)->find();
        if (empty($user)) {
            $user = UserModel::mobile_register($mobile, '*', $ref);
            if (!$user) return ['code' => 400, 'msg' => '注册失败，请重试'];
        }

        $userStatus = true;
        if ($user['status'] != 1) $userStatus = false;
        $param = [
            'uid'         => $user['id'],
            'type'        => 2,
            'user_status' => $userStatus ? 1 : 2,
            'status'      => $userStatus ? 1 : 2,
            'login_type'  => LoginType::LOGIN_TYPE_PHONE->value
        ];
        UserBehaviorLog::log($param);
        if (!$userStatus) return ['code' => 400, 'msg' => '当前账号状态异常，请联系管理员'];

        $token         = UserToken::loginToken($user, LoginType::LOGIN_TYPE_PHONE->value);
        $data['token'] = $token['token'] ?? '';

        $uid      = $user['id'];
        //会员过期状态，1正常 2过期
        $where2[]           = ['user_id', '=', $uid];
        $where2[]           = ['status', '=', 1];
        $where2[]           = ['order_status', '<>', 3];
        $data['is_vip'] = OrderVipcart::getFieldByOrder($where2, 'status', 'pay_time desc') ? 1 : 2;

        $data['uid']    = $uid;

        return ['code' => 200, 'msg' => '', 'data' => $data];
    }
}
